package com.getan.boot.module.system.controller;

import com.getan.boot.common.ResponseBuilder;
import com.getan.boot.common.ResponseCodeData;
import com.getan.boot.common.annotation.OperateLog;
import com.getan.boot.common.holder.security.SecurityContextHolder;
import com.getan.boot.common.utils.Preconditions;
import com.getan.boot.module.system.constant.ErrorCode;
import com.getan.boot.module.system.domain.bo.ProfileBO;
import com.getan.boot.module.system.entity.UserEntity;
import com.getan.boot.module.system.service.persistent.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 个人中心
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/profile")
public class ProfileController {

    private final String MODULE = "用户管理";
    private final UserService userService;

    @PostMapping("info")
    public ResponseCodeData<UserEntity> info() {
        return ResponseBuilder.ok(userService.getById(SecurityContextHolder.getCurrentUserId()));
    }

    @OperateLog(module = MODULE, businessType = "UPDATE_PROFILE")
    @PostMapping("updateInfo")
    public ResponseCodeData<Void> updateInfo(@RequestBody @Valid ProfileBO.UpdateInfoBO bo) {
        UserEntity entity = new UserEntity();
        BeanUtils.copyProperties(bo, entity);
        entity.setId(SecurityContextHolder.getCurrentUserId());
        userService.canUpdate(entity);
        userService.update(entity);
        return ResponseBuilder.ok();
    }

    @OperateLog(module = MODULE, businessType = "UPDATE_PASSWORD")
    @PostMapping("updatePassword")
    public ResponseCodeData<Void> updatePassword(@RequestBody @Valid ProfileBO.UpdatePasswordBO bo) {
        Preconditions.check(() -> !Objects.equals(bo.getNewPwd(), bo.getNewPwdRepeat()), ErrorCode.PROFILE_PWD_NEQ);
        userService.updatePassword(SecurityContextHolder.getCurrentUserId(), bo.getOldPwd(), bo.getNewPwd());
        return ResponseBuilder.ok();
    }

}
